<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagPivotContract;
use MoChat\Plugin\RoomTrack\Constants\Event;
use MoChat\Plugin\RoomTrack\Constants\EventName;
use MoChat\Plugin\RoomTrack\Contract\RoomTrackContract;

/**
 * 客户画像-客户群标签列表.
 *
 * Class Store
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagPivotContract
     */
    protected $roomTagPivotService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Inject
     * @var WorkRoomContract
     */
    protected $workRoom;

    /**
     * @Inject
     * @var RoomTagContract
     */
    protected $roomTagService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var RoomTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/roomTag/store", methods="POST")
     */
    public function handle(): array
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['roomId'] = (int) $this->request->input('roomId');
        $params['tagIds'] = $this->request->input('tagIds');

        // 验证参数
        $this->validated($params);

        # # 数据操作
        Db::beginTransaction();
        try {
            # # 删除群标签
            $roomTags = $this->roomTagPivotService->getRoomTagPivotsByRoomIdTagId($params['roomId'], 0, ['id', 'room_tag_id']);
            foreach ($roomTags as $item) {
                if (! in_array($item['roomTagId'], $params['tagIds'], true)) {
                    $this->roomTagPivotService->deleteRoomTagPivot($item['id']);
                }
            }
            # # 添加群标签
            $id = 0;
            foreach ($params['tagIds'] as $tagId) {
                if (! empty($this->roomTagPivotService->getRoomTagPivotsByRoomIdTagId($params['roomId'], $tagId))) {
                    continue;
                }
                $data = [
                    'room_id' => $params['roomId'],
                    'employee_id' => user()['id'],
                    'room_tag_id' => $tagId,
                    'type' => 2,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $id = $this->roomTagPivotService->createRoomTagPivot($data);
            }
            // 记录轨迹+
            $employee = $this->workEmployee->getWorkEmployeeById(user()['id'], ['name']);
            $room = $this->workRoom->getWorkRoomById($params['roomId'], ['name']);
            $tags = $this->roomTagService->getRoomTagsById($params['tagIds'], ['name']);
            $tagName = '';
            foreach ($tags as $item) {
                $tagName .= " 「{$item['name']}」";
            }
            $content = "管理员{$employee['name']}给群聊【{$room['name']}】添加了标签{$tagName}";
            $this->recordTrack($params['roomId'], $content, $id);
            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加群标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'roomId' => 'required|integer',
            'tagIds' => 'required|array',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'roomId.required' => '客户群id 必传',
            'tagIds.required' => '标签id 必传',
        ];
    }

    /**
     * 记录轨迹.
     */
    private function recordTrack(int $roomId, string $content, int $relationId): void
    {
        $jsonContact = [
            'title' => EventName::TAG,
            'content' => $content,
        ];
        $data = [
            'room_id' => $roomId,
            'employee_id' => user()['id'],
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'relation_id' => $relationId,
            'event' => Event::DYNAMIC,
        ];

        $res = $this->track->createRoomTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
